/*
 * 同城信息发布
 * author: huangbin
 * 技术支持微信号：wxid_i8yk4fp0uep322
 * 开源协议：MIT
 *  *Copyright (c) 2018 https:/www.tczhb.club All rights reserved.
 */
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var auth = require('../../utils/auth.js');
var WxParse = require('../../wxParse/wxParse.js');
var wxApi = require('../../utils/wxApi.js')
var wxRequest = require('../../utils/wxRequest.js')
var app = getApp();
let isFocusing = false

Page({
  data: {
    title: '文章内容',
    detail: {},
    commentsList: [],
    ChildrenCommentsList: [],
    commentCount: '',
    detailDate: '',
    commentValue: '',
    wxParseData: [],
    display: 'none',
    page: 1,
    isLastPage: false,
    parentID: "0",
    focus: false,
    placeholder: "输入评论",
    postID: null,
    scrollHeight: 0,
    postList: [],
    link: '',
    dialog: {
      title: '',
      content: '',
      hidden: true
    },
    content: '',
    isShow: false,//控制menubox是否显示
    isLoad: true,//解决menubox执行一次  
    menuBackgroup: false,
    likeImag: "like.png",
    likeList: [],
    likeCount: 0,
    displayLike: 'none',
    userid: "",
    toFromId:"",
    commentdate:"",
    flag: 1
  },
  onLoad: function (options) {
    if (!app.globalData.isGetOpenid) {
      auth.getUsreInfo();
    }
    this.fetchDetailData(options.id);
  },
  showLikeImg: function () {
    var self = this;
    var flag = false;
    var _likes = self.data.detail.avatarurls;
    var likes = [];
    for (var i = 0; i < _likes.length; i++) {
      var avatarurl = "../../images/gravatar.png";
      if (_likes[i].avatarurl.indexOf('wx.qlogo.cn') != -1) {
        avatarurl = _likes[i].avatarurl;
      }
      likes[i] = avatarurl;
    }
    var temp = likes;
    self.setData({
      likeList: likes
    });
  },
  onShareAppMessage: function (res) {
    this.ShowHideMenu();
    console.log(res);
    return {
      title: '分享"' + app.globalData.app_name + '"的信息：' + util.removeHTML(this.data.detail.post_content),
      path: 'pages/detail/detail?id=' + this.data.detail.id,
      imageUrl: this.data.detail.more.photos[0].url,
      success: function (res) {
        // 转发成功
        console.log(res);
      },
      fail: function (res) {
        console.log(res);
        // 转发失败
      }
    }
  },
  copyLink: function (url) {
      //this.ShowHideMenu();
      wx.setClipboardData({
          data: url,
          success: function (res) {
              wx.getClipboardData({
                  success: function (res) {
                      wx.showToast({
                          title: '链接已复制',
                          image: '../../images/link.png',
                          duration: 2000
                      })
                  }
              })
          }
      })
  },
  clickLike: function (e) {
      var id = e.target.id;
      var self = this;
      if (id == 'likebottom') {
          this.ShowHideMenu();
      }

      if (app.globalData.isGetOpenid) {
          var data = {
              id: self.data.postID
          };
          var url = Api.postLikeUrl();
          var postLikeRequest = wxRequest.postRequest(url, data);
          postLikeRequest
              .then(response => {
                  if (response.data.status == '200') {
                      var _likeList = []
                      var _like = app.globalData.userInfo.avatarUrl;
                      _likeList.push(_like);
                      var tempLikeList = _likeList.concat(self.data.likeList);
                      var _likeCount = parseInt(self.data.likeCount) + 1;
                      self.setData({
                          likeList: tempLikeList,
                          likeCount: _likeCount,
                          displayLike: 'block'
                      });
                      wx.showToast({
                          title: '谢谢点赞',
                          icon: 'success',
                          duration: 900,
                          success: function () {
                          }
                      })
                  }
                  else if (response.data.code == '0') {
                      console.log(response.data.msg);
                      wx.showToast({
                          title: '谢谢，已赞过',
                          icon: 'success',
                          duration: 900,
                          success: function () {
                          }
                      })
                  }
                  else {
                    console.log(response.data.msg);
                  }
                  self.setData({
                      likeImag: "like-on.png"
                  });
              })
      }
      else {
        auth.getUsreInfo();
      }
  },
  getIslike: function () { //判断当前用户是否点赞
      var self = this;
      if (app.globalData.isGetOpenid) {
          var data = {
              id: self.data.postID
          };
          var url = Api.postIsLikeUrl();
          var postIsLikeRequest = wxRequest.postRequest(url, data);
          postIsLikeRequest
              .then(response => {
                  if (response.data.code == '200') {
                    if (response.data.data){
                      self.setData({
                        likeImag: "like-on.png"
                      });
                      console.log("已赞过");
                    }
                  }
              })

      }
  },

  goHome: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },

  //获取文章内容
  fetchDetailData: function (id) {
      var self = this;
      var getPostDetailRequest = wxRequest.getRequest(Api.getPostByID(id));
      var res;
      var _displayLike = 'none';
      getPostDetailRequest
          .then(response => {
              res = response;
              if (response.data.data.comment_count != null && response.data.data.comment_count != '') {
                  self.setData({
                    commentCount: "有" + response.data.data.comment_count + "条评论"
                  });
              };
              var _likeCount = response.data.data.post_like;
              if (response.data.data.post_like != '0') {
                  _displayLike = "block"
              }
              response.data.data.dataStr = util.getDateDiff(response.data.data.published_time);
              WxParse.wxParse('article', 'html', response.data.data.post_content, self, 5); 
              self.setData({
                  detail: response.data.data,
                  likeCount: _likeCount,
                  postID: id,
                  //link: response.data.link,
                  detailDate: util.cutstr(response.data.data.published_time, 10, 1),
                  display: 'block',
                  displayLike: _displayLike
              });
              // 调用API从本地缓存中获取阅读记录并记录
              var logs = wx.getStorageSync('readLogs') || [];
              // 过滤重复值
              if (logs.length > 0) {
                  logs = logs.filter(function (log) {
                      return log[0] !== id;
                  });
              }
              // 如果超过指定数量
              if (logs.length > 19) {
                  logs.pop();//去除最后一个
              }
              logs.unshift([id, res.data.data.post_title, response.data.data.category_id]);
              wx.setStorageSync('readLogs', logs);
              //end 
          })
          .then(response => {
              wx.setNavigationBarTitle({
                title: res.data.data.categories[0].name + "-信息详情"
              });

          }).then(response => {//获取评论
              self.fetchCommentData(self.data, '0');
          }).then(response => {//获取是否已经点赞
              if (app.globalData.isGetOpenid) {
                  self.getIslike();
              }
          })
          .catch(function (response) {

          }).finally(function (response) {

          });
  },
  
  //获取评论
  fetchCommentData: function (data, flag) {
      var self = this;
      if (!data) data = {};
      if (!data.page) data.page = 1;
      data.pid = '0';

      self.setData({
          commentsList: [],
      });
      var getCommentsRequest = wxRequest.getRequest(Api.getComments(data));
      getCommentsRequest
          .then(response => {
              if (response.statusCode == 200) {
                  if (response.data.data.length < 100) {
                      self.setData({
                          isLastPage: true
                      });
                  }
                  if (response.data.data) {
                      self.setData({
                          //commentsList: response.data, 
                          commentsList: self.data.commentsList.concat(response.data.data.map(function (item) {
                              var strSummary = util.removeHTML(item.content);
                              var dateStr = item.create_time;
                              dateStr = dateStr.replace("T", " ");
                              var strdate = util.getDateDiff(dateStr);
                              item.date = strdate;
                              item.dateStr = dateStr;
                              item.summary = strSummary;
                              return item;
                          }))
                      });
                  }
              }
          })
      .catch(response=>{
          console.log(response.data.message);
      })
  },

  //获取回复
  fetchChildrenCommentData: function (data, flag) {
      var self = this;
      var getChildrenCommentsRequest = wxRequest.getRequest(Api.getChildrenComments(data));
      getChildrenCommentsRequest
          .then(response => {
              if (response.data) {
                  self.setData({
                      ChildrenCommentsList: self.data.ChildrenCommentsList.concat(response.data.map(function (item) {
                          var strSummary = util.removeHTML(item.content.rendered);
                          var strdate = item.date
                          item.summary = strSummary;

                          item.date = util.formatDateTime(strdate);
                          if (item.author_url.indexOf('wx.qlogo.cn') != -1) {
                              if (item.author_url.indexOf('https') == -1) {
                                  item.author_url = item.author_url.replace("http", "https");
                              }
                          }
                          else {
                              item.author_url = "../../images/gravatar.png";
                          }
                          return item;
                      }))

                  });

              }
              setTimeout(function () {
                  //wx.hideLoading();
                  if (flag == '1') {
                      wx.showToast({
                          title: '评论发布成功。',
                          icon: 'success',
                          duration: 900,
                          success: function () {

                          }
                      })
                  }
              }, 900);
          })
  },
  //显示或隐藏功能菜单
  ShowHideMenu: function () {
      this.setData({
          isShow: !this.data.isShow,
          isLoad: false,
          menuBackgroup: !this.data.false
      })
  },
  //点击非评论区隐藏功能菜单
  hiddenMenubox: function () {
      this.setData({
          isShow: false,
          menuBackgroup: false
      })
  },
  //底部刷新
  loadMore: function (e) {
      var self = this;
      if (!self.data.isLastPage) {
          self.setData({
              page: self.data.page + 1
          });
          console.log('当前页' + self.data.page);
          this.fetchCommentData(self.data, '0');
      }
      else {
          wx.showToast({
              title: '没有更多内容',
              mask: false,
              duration: 1000
          });
      }
  },
  replay: function (e) {
      var self = this;
      var id = e.target.dataset.id;
      var name = e.target.dataset.name;
      var userid = e.target.dataset.userid;
      var commentdate = e.target.dataset.commentdate;
      isFocusing = true;
      self.setData({
          parentID: id,
          placeholder: "回复" + name + ":",
          focus: true,
          userid: userid,
          commentdate: commentdate
      });
      console.log('replay', isFocusing);
  },
  onReplyBlur: function (e) {
      var self = this;
      console.log('onReplyBlur', isFocusing);
      if (!isFocusing) {
          {
              const text = e.detail.value.trim();
              if (text === '') {
                  self.setData({
                      parentID: "0",
                      placeholder: "输入评论",
                      userid: "",
                      toFromId:"",
                      commentdate:""
                  });
              }

          }
      }
      console.log(isFocusing);
  },
  onRepleyFocus: function (e) {
      var self = this;
      isFocusing = false;        
      console.log('onRepleyFocus', isFocusing);
      if (!self.data.focus) {
          self.setData({ focus: true })
      }


  },
  //提交评论
  formSubmit: function (e) {
    if (!app.globalData.isGetOpenid) {
      auth.getUsreInfo();
    }
    else{
      var self = this;
      var comment = e.detail.value.inputComment;
      var parent = self.data.parentID;
      var postID = e.detail.value.inputPostID;
      var commentdate = self.data.commentdate;
      if (comment.length === 0) {
        self.setData({
          'dialog.hidden': false,
          'dialog.title': '提示',
          'dialog.content': '没有填写评论内容。'
        });
      }
      else {
        if (app.globalData.isGetOpenid) {
          var data = {
            object_id: postID,
            table_name: 'portal_post',
            content: comment,
            parent_id: parent
          };
          var url = Api.postWeixinComment();
          var postCommentRequest = wxRequest.postRequest(url, data);
          postCommentRequest
          .then(res => {
            if (res.statusCode == 200) {
              if (res.data.code == '200') {
                self.setData({
                  content: '',
                  parentID: "0",
                  userid: 0,
                  placeholder: "输入评论",
                  focus: false,
                  commentsList: []
                });
                setTimeout(function () {
                  wx.showToast({
                    title: '评论发布成功。',
                    icon: 'success',
                    duration: 900,
                    success: function () {
                    }
                  })
                }, 900);
                console.log(res.data.msg);
                self.fetchCommentData(self.data, '1');
              }
              else if (res.data.status == '500') {
                self.setData({
                  'dialog.hidden': false,
                  'dialog.title': '提示',
                  'dialog.content': '评论失败，请稍后重试。'
                });
              }
            }
          })
          .catch(response => {
            console.log(response)
            self.setData({
              'dialog.hidden': false,
              'dialog.title': '提示',
              'dialog.content': '评论失败,' + response
            });
          })
        }
      }
    }
  },
  confirm: function () {
      this.setData({
          'dialog.hidden': true,
          'dialog.title': '',
          'dialog.content': ''
      })
  },
  creatPoster: function () {
      var self = this;
      self.ShowHideMenu();
      if (self.data.posterImageUrl)
      {
          url = '../poster/poster?posterImageUrl=' + posterImageUrl;
          wx.navigateTo({
              url: url
          })

          return true;
      }
      var postid = self.data.detail.id;
      var title = self.data.detail.title.rendered;        
      var path = "pages/detail/detail?id="+postid;
      var postImageUrl="";
      if (self.data.detail.content_first_image)
      {
          postImageUrl = self.data.detail.content_first_image;

      }
      wx.showLoading({
          title: "正在生成图片",
          mask: false,
      });
      
      if (app.globalData.isGetOpenid) {
          var openid = app.globalData.openid;
          var data = {
              postid: postid,
              title: title,
              path: path,
              postImageUrl: postImageUrl,
              openid: openid                
          };
          var url = Api.creatPoster();
          var posterImageUrl = Api.getPosterUrl() + "poster-" + postid+".jpg";
          var creatPosterRequest = wxRequest.postRequest(url, data);
          creatPosterRequest.then(response => {
              if (response.statusCode == 200) {
                  if (response.data.status == '200') {                       
                      url = '../poster/poster?posterImageUrl=' + posterImageUrl;
                      wx.navigateTo({
                          url: url
                      })

                  }
                  else{

                      console.log(response);

                  }
              }
              else
              {
                  console.log(response);
              }

          }).catch(response => {
              console.log(response);                
              }).finally(function (response) {
                  wx.hideLoading();
              });

          
      }   

  },
  //图片预览
  detailePreviewImage: function (e) {
    var that = this;
    var imgs = e.currentTarget.dataset.imgs;
    var urls = [];
    for (var i = 0, len = imgs.length; i < len; i++) {
      urls.push(imgs[i]['url']);
    }
    wx.previewImage({
      current: e.currentTarget.dataset.img,
      urls: urls
    })
  },
  /**
  * 打开地图标注
  */
  detail_open_map: function (e) {
    //console.log(e.currentTarget.dataset)
    var lat = e.currentTarget.dataset.lat;
    var lon = e.currentTarget.dataset.lon;
    if (lat != '0') {
      wx.openLocation({
        latitude: parseFloat(lat),
        longitude: parseFloat(lon),
        scale: 28
      });
    } else {
      wx.showToast({
        image: '../../resource/images/static/error.png',
        title: '座标错误,无法定位!',
      });
    }
  }
})